#include "OutputConfig.h"

#include "UUIDGenerator.h"

using namespace platform;

namespace config {



void OutputConfig::do_save(void) const 
{
	RegistryHelper::RegistryKey key(RegistryHelper::RK_ABPA_BASE, REGISTRY_ROOT_KEY);
	key.setValue(REGISTRY_VALUE_LOCATION, m_sOutputLocation);
}


static bool checkFileExists(const platform::XString &fname) {
	DWORD dw = ::GetFileAttributes(fname.c_str());
	return (dw != 0xffffffff);	
}

const platform::XString & OutputConfig::getProcessOutputFile(const platform::XString &ext) const
{
	// NOTE: the file IDs are expected to be generated unique. To be on
	// the safe side, we allow up to 5 attempts in case that the generated
	// id is already used by some file.
	int attempts = 0;
	do {
		attempts++;

		// generate unique string
		UUIDGenerator gen;
		XString sUUID;
		gen.Create(sUUID);

		// append UUID to path
		m_sProcOutputFile = m_sOutputLocation;
		m_sProcOutputFile += _T('\\');
		m_sProcOutputFile += sUUID;
		m_sProcOutputFile += _T('.');
		m_sProcOutputFile += ext;
	} while (!checkFileExists(m_sProcOutputFile) && attempts < 5);

	return m_sProcOutputFile;
}


} // end namespace